<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-09-22 14:31:55
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 加料单
 */

namespace App\Http\Services\Finance;


use App\Http\Services\Service;
use App\Repositories\FinanceFixedAssetRepository;
use App\Repositories\FinanceVoucherDetailsRepository;
use App\Repositories\FinanceVoucherRepository;

/**
 * @property FinanceFixedAssetRepository $repository
 * @property FinanceVoucherRepository $voucher
 */
class FixedAssetService extends Service
    {

    public function boot(FinanceFixedAssetRepository $repository, FinanceVoucherRepository $voucher)
        {
        $this->repository = $repository;
        $this->voucher    = $voucher;
        }

    public function list()
        {
        return $this->repository->condition()->getGrid();
        }
    protected function save()
        {
        $gdata    = $this->repository->autosave(request()->toArray());
        $debit_id = $credit_id = 0;
        if ($gdata->voucher) {
            [$credit_id, $debit_id] = $gdata->voucher->details->map(function ($v)
                {
                return $v->id;
                });
            }

        $details = [];
        $summary = $gdata->summary;
        if (isEmpty($summary)) {
            $summary = "{$gdata->add_method->name}[{$gdata->company->name}]-固定资产";
            }
        //贷 应付账款/在建工程
        $details[] = $this->voucher->mergeVoucher($gdata->add_method_id, $summary, 0, $gdata->amount, $gdata->toArray(), $credit_id);
        //借 固定资产
        $details[] = $this->voucher->mergeVoucher(1601, $summary, $gdata->amount, 0, $gdata->toArray(), $debit_id);

        $this->voucher->CreateVoucher($gdata->billdate, 1, $details, $gdata, $gdata->voucher?->id);
        return $gdata;
        }


    protected function delete()
        {
        $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            //删除对应凭证
            $this->voucher->RemoveVoucher($v);
            $v->delete();
            });
        }

    }